package com.xncoding.jwt.service;

import cn.hutool.core.lang.Snowflake;
import com.xncoding.jwt.service.entity.User;
import com.xncoding.jwt.service.entity.UserMapper;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@EnableCaching
public class UserService {
    @Resource private Snowflake snowflake;
    @Resource    private UserMapper userMapper;
    /**
     * Cacheable
     * value：缓存key的前缀。 或配置 cacheNames = "userCache",
     * key：缓存key的后缀。
     * sync: 设置如果缓存过期是不是只放⼀个请求去请求数据库，其他请求阻塞，默认是false。
     * */
    @Cacheable(value = "user",  key = "#id")
    // @Cacheable(cacheNames = "caffeineCacheManager", key = "#root.targetClass.simpleName+'-getSessionId'", unless = "!#result.success")
    public User findById(Integer id) {
        return userMapper.selectById(id);
    }

    @Cacheable(value = "user",  key = "#user.id")
    public User insertUser(User user) {
        user.setSt(snowflake.nextIdStr());
        userMapper.insert(user);
        return user;
    }
    // 修改缓存
    @CachePut(value = "user",  key = "#user.id")
    public void updateUser(User user) {
        userMapper.updateById(user);
    }
    // 清除缓存
    @CacheEvict(value = "user",  key = "#id")
    public void clearCache(Integer id) {

    }
    public void deleteUser(Integer id) {
        userMapper.deleteById(id);
    }

}
